package com.cjd.view

import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.animation.Animation
import android.view.animation.CycleInterpolator
import android.view.animation.TranslateAnimation
import com.cjd.common.R

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2020-3-25
 */
class ClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.editTextStyle
) : androidx.appcompat.widget.AppCompatEditText(context, attrs, defStyleAttr),
    OnFocusChangeListener, TextWatcher {

    protected var mClearDrawable: Drawable? = null
    private var drawableWidth = 0
    private var drawableHeight = 0
    var onClearIconClickListener: (() -> Unit)? = null

    init {
        val size = resources.getDimensionPixelSize(R.dimen.dip_fourteen)
        drawableHeight = size
        drawableWidth = size

        attrs?.let {
            val typedArray: TypedArray =
                context.obtainStyledAttributes(it, R.styleable.ClearEditText)

            mClearDrawable = typedArray.getDrawable(R.styleable.ClearEditText_cet_drawable_icon)
            drawableWidth = typedArray.getDimensionPixelOffset(
                R.styleable.ClearEditText_cet_drawable_width,
                drawableWidth
            )
            drawableHeight = typedArray.getDimensionPixelOffset(
                R.styleable.ClearEditText_cet_drawable_height,
                drawableHeight
            )

            typedArray.recycle()
        }

        initClearIconDrawable()
    }

    /**
     * 当ClearEditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
     */
    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        text?.let {
            if (hasFocus) {
                setClearIconVisible(it.isNotEmpty())
            } else {
                setClearIconVisible(false)
            }
        }
    }

    override fun afterTextChanged(s: Editable?) {

    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)

        text?.let {
            setClearIconVisible(it.isNotEmpty())
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
    }

    private fun initClearIconDrawable() {
        if (mClearDrawable == null) {
            //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
            // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,2是获得右边的图片  顺序是左上右下（0,1,2,3,）
            mClearDrawable = compoundDrawables[2]
            if (mClearDrawable == null) {
                mClearDrawable = resources.getDrawable(R.drawable.view_clear_edittext_close)
            }
        }
        mClearDrawable?.let {
            it.setBounds(0, 0, drawableWidth, drawableHeight)
            // 默认设置隐藏图标
            setClearIconVisible(false)
            // 设置焦点改变的监听
            onFocusChangeListener = this
            // 设置输入框里面内容发生改变的监听
            addTextChangedListener(this)
        }
    }

    fun setClearDrawable(drawable: Drawable) {
        mClearDrawable = drawable
        initClearIconDrawable()
    }


    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     * @param visible
     */
    protected fun setClearIconVisible(visible: Boolean) {

        val right = if (visible) mClearDrawable else null
        setCompoundDrawables(
            compoundDrawables[0],
            compoundDrawables[1], right, compoundDrawables[3]
        )
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (compoundDrawables[2] != null) {
            event?.let {
                when (it.action) {
                    MotionEvent.ACTION_UP -> {
                        mClearDrawable?.let { drawable ->
                            val touchable = (event.x > (width
                                    - paddingRight - drawable.intrinsicWidth)
                                    && event.x < width - paddingRight)
                            if (touchable) {
                                if (onClearIconClickListener == null)
                                    this.setText("")
                                else
                                    onClearIconClickListener?.invoke()
                            }
                        }

                    }
                    else -> {

                    }
                }
            }
        }
        return super.onTouchEvent(event)
    }


    /**
     * 设置晃动动画
     */
    fun setShakeAnimation() {
        this.animation = shakeAnimation(5)
    }


    /**
     * 晃动动画
     * @param counts 1秒钟晃动多少下
     * @return
     */
    fun shakeAnimation(counts: Int): Animation? {
        val translateAnimation: Animation =
            TranslateAnimation(0f, 10f, 0f, 0f)
        translateAnimation.interpolator = CycleInterpolator(counts.toFloat())
        translateAnimation.duration = 1000
        return translateAnimation
    }
}